package com.lqk.pipe;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.Pipe;

public class PipeDemo {
    public static void main(String[] args) throws Exception {
        // 1 获取管道
        Pipe pipe = Pipe.open();

        // 2 获取sink通道
        Pipe.SinkChannel sinkChannel = pipe.sink();

        // 3 创建Buffer，写入数据
        ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
        byteBuffer.clear();
        byteBuffer.put("lqk".getBytes());
        byteBuffer.flip();

        // 4 向sink通道写入数据
        sinkChannel.write(byteBuffer);

        // 5 获取source通道
        Pipe.SourceChannel sourceChannel = pipe.source();

        // 6 读取数据
//        ByteBuffer sourceBuffer = ByteBuffer.allocate(1024);
        byteBuffer.flip();
        int length = sourceChannel.read(byteBuffer);

        System.out.println(new String(byteBuffer.array(),0,length));

        // 7 关闭通道
        sourceChannel.close();
        sinkChannel.close();
    }
}
